package com.ifast.api.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ifast.api.util.JWTUtil;
import com.ifast.common.service.RedisParentManager;
import com.ifast.common.type.EnumErrorCode;
import com.ifast.common.utils.Const;
import com.ifast.common.utils.GjpLogger;
import com.ifast.common.utils.SmsUtil;
import com.ifast.sys.domain.DeptDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.DeptService;
import com.ifast.sys.service.UserService;
import com.luculent.util.extension.api.Result;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.PinyinUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;

/**
 * <pre>
 *  基于jwt实现的API测试类
 * </pre>
 * 
 * <small> 2018年4月27日 | Aron</small>
 */
@RestController
@RequestMapping("/api/user/")
public class ApiUserController {

    @Autowired
    private UserService sysUserServiceImpl;

    @Autowired
    private RedisParentManager redisParentService;

    @Autowired
    private DeptService deptService;


    @GetMapping("getUserInfo")
    @ApiOperation(value = "获取个人信息",httpMethod = "GET")
    public Result<?> getUserInfo( @ApiParam(name = "Authorization", required = true, value = "token")  @RequestHeader String Authorization) {
        return this.sysUserServiceImpl.getUserInfoForApp(Authorization);
    }

    @PostMapping("resetPassword")
    @ApiOperation(value = "修改密码",httpMethod = "GET")
    public Result<?> resetPassword(
            @ApiParam(name = "oldPassword", required = true, value = "旧密码") @RequestParam("oldPassword") String oldPassword,
            @ApiParam(name = "newPassword", required = true, value = "新密码") @RequestParam("newPassword") String newPassword,
            @ApiParam(name = "Authorization", required = true, value = "token") @RequestHeader("Authorization") String token
    ) {
        return this.sysUserServiceImpl.updatePassword(token,oldPassword,newPassword);
    }


    @GetMapping(value = "txlDwList")
    @ApiOperation( value = "通讯录单位查询", httpMethod = "GET",notes="默认返回当前登录用户所在单位和下一级单位数据")
    @ApiResponse(code = 200, message = "success", response = Result.class)
    public Result<?> txlDwList(
            @ApiParam(name = "Authorization", required = true, value = "token") @RequestHeader("Authorization") String token){
        try {
            Result<Map<String,Object>> Result = new Result<>();
            String userId = JWTUtil.getUserId(token);
            UserDO userDTODq = this.sysUserServiceImpl.selectById(userId);
            DeptDO deptDOW = new DeptDO();
            deptDOW.setId(userDTODq.getDeptId());
            deptDOW.setDwCode(userDTODq.getDwCode());
            deptDOW.setDwCodeLength(userDTODq.getDwCode().length()+4);
            List<DeptDO> deptDOList = this.deptService.listDeptNextByCode(deptDOW);
            if(CollectionUtil.isNotEmpty(deptDOList)){
                for (DeptDO deptDO : deptDOList) {
                    Map<String,Object> resmap = Maps.newHashMap();
                    resmap.put("deptId",deptDO.getId());
                    resmap.put("dwName",deptDO.getName());
                    Result.setData(resmap);
                }
            }
            return Result;
        } catch (Exception e) {
            GjpLogger.error(e.toString(),e);
            return Result.fail(EnumErrorCode.apiYwClFailed.getCode(), EnumErrorCode.apiYwClFailed.getMsg());
        }
    }

    @PostMapping(value = "txkList")
    @ApiOperation( value = "通讯录用户列表", httpMethod = "POST",notes="默认返回前100条用户数据,如果单位id(deptId)为空，默认查询当前登录单位下所有用户的前100条")
    @ApiResponse(code = 200, message = "success", response = Result.class)
    public Result<?> list(
            @ApiParam(name = "deptId", value = "单位id") @RequestParam(value = "deptId",required=false) String deptId,
            @ApiParam(name = "name", value = "姓名") @RequestParam(value = "name",required=false) String name,
            @ApiParam(name = "Authorization", required = true, value = "token") @RequestHeader("Authorization") String token){
        try {
            Result<Map<String,Object>> Result = new Result<>();
            UserDO userDTODq = new UserDO();
            if(StrUtil.isNotBlank(deptId)){
                DeptDO deptDO = this.deptService.selectById(deptId);
                userDTODq.setDwCode(deptDO.getDwCode());
            }else{
                String userId = JWTUtil.getUserId(token);
                userDTODq = this.sysUserServiceImpl.selectById(userId);
                DeptDO deptDO = this.deptService.selectById(userDTODq.getDeptId());
                userDTODq.setDwCode(deptDO.getDwCode());
            }
            userDTODq.setName(StrUtil.isNotBlank(name)?name:"");
            List<UserDO> userDOList = this.sysUserServiceImpl.listUser(userDTODq);
            for (UserDO userDO : userDOList) {
                DeptDO deptDOPar = null;
                if(userDO.getDwCode().length() >= 8){
                    String dwCodeS = userDO.getDwCode().substring(0,8);
                    Wrapper wrapperD = new EntityWrapper<DeptDO>();
                    wrapperD.eq("dw_code",dwCodeS);
                    deptDOPar = this.deptService.selectOne(wrapperD);
                }
                Map<String,Object> map = Maps.newHashMap();
                map.put("name",userDO.getName());
                map.put("zw",StrUtil.isNotBlank(userDO.getZw()) ? userDO.getZw() : "");
                map.put("deptName",userDO.getDeptName());
                map.put("namePinyin",PinyinUtil.getPinYin(userDO.getName()));
                map.put("tel",userDO.getUsername());
                map.put("gongSi",deptDOPar != null ? deptDOPar.getName() : "");
                Result.setData(map);
            }
            return Result;
        } catch (Exception e) {
            GjpLogger.error(e.toString(),e);
            return Result.fail(EnumErrorCode.apiYwClFailed.getCode(), EnumErrorCode.apiYwClFailed.getMsg());
        }
    }


    @PostMapping("updateUserPic")
    @ApiOperation(value = "更新个人头像",httpMethod = "POST")
    public Result<?> updateUserPic(@RequestHeader String Authorization, HttpServletRequest request) {
        try {
            return this.sysUserServiceImpl.updateUserInfoZjForApp(Authorization,request);
        } catch (Exception e) { 
            GjpLogger.error(e.toString(),e);
            return Result.fail(EnumErrorCode.apiYwClFailed.getCode(), EnumErrorCode.apiYwClFailed.getMsg());
        } 
    }


    @PostMapping("forgetPassword")
    @ApiOperation(value ="忘记密码",httpMethod = "POST")
    public Result<?> forgetPassword(
            @ApiParam(name = "userName", required = true, value = "账号") @RequestParam("userName") String userName,
            @ApiParam(name = "code", required = true, value = "验证码") @RequestParam("code") String code,
            @ApiParam(name = "newPassWord", required = true, value = "新密码") @RequestParam("newPassWord") String newPassWord
    ) {
        return this.sysUserServiceImpl.forgetPassword(code,userName,newPassWord);
    }



    @GetMapping("getSmsCode")
    @ApiOperation(value ="获取验证码",httpMethod = "GET")
    public Result<?> getSmsCode(
            @ApiParam(name = "tel", required = true, value = "手机号码") @RequestParam("tel") String tel) {
        Result<Map<String,Object>> Result = new Result<>();
        //判断用户是否存
        UserDO user = new UserDO();
        user.setUsername(tel);
        user = sysUserServiceImpl.selectOne(new EntityWrapper<>(user));
        if(user == null || user.getId() == null){
        	 Result.setCode(EnumErrorCode.apiYwClFailed.getCode());
             Result.setMsg("用户不存在!");
             return Result;
        }
        //判断规定时间内是否已发送
        if(redisParentService.containsValueKey(tel)){
            Result.setCode(EnumErrorCode.apiYwClFailed.getCode());
            Result.setMsg("验证码已发送!");
            return Result;
        }
        List<String> params = Lists.newArrayList();
        int[] sjz = NumberUtil.generateRandomNumber(0,9,4);
        StringBuilder codez = new StringBuilder();
        for (int z : sjz) {
            codez.append(z);
        }
        redisParentService.cacheValue(tel,codez.toString(),Const.SMS_TIME_OUT); 
        params.add(codez.toString());
        SmsSingleSenderResult smsSingleSenderResult = SmsUtil.singleSend(tel,params,
                316184);
        int fee = smsSingleSenderResult.fee;
        if(fee != 0){
        	Map<String,Object> data = Maps.newHashMap();
        	data.put("code",codez.toString());
        	Result.setData(data);
        }else{
            Result.setCode(EnumErrorCode.apiYwClFailed.getCode());
            Result.setMsg(EnumErrorCode.apiYwClFailed.getMsg());
        }
        return Result;
    }

}
